<template>
  <div class="hello">
    <!--index start-->
    <div class="wrapper">
      <div class="content-index flex_box">
        <!--map start-->
        <div class="map flex" id="map-container">
          <!--自己加的搜索框  start-->
          <div class="search">
            <div class="search-box-new">
              <input id="aaa" class="box-style" type="search" v-model="searchData" @focus="changeStatus"/>
              <button class="btn-search" @click="searchBtn"></button>
            </div>
            <!--输入结果下拉框  start-->
            <div class="serResult" v-if="searchShow">
              <ul>
                <li v-for="(item, index) in searchList" :key="index" v-if="item.areaName.indexOf(searchData) != -1"
                    @click="onSearchItem(item.areaCode, item.areaName)">
                  <p class="title" v-text="item.areaName">哒哒街道</p>
                  <p><span class="lfName">维保电梯数</span><span v-text="item.number">5部</span></p>
                </li>
              </ul>
            </div>
            <!--输入结果下拉框  end-->
          </div>
          <!--自己加的搜索框  end-->
          <el-amap id="amapDemo" ref="map" vid="amapDemo" pitch="30" viewMode="3D" buildingAnimation="false"
                   showIndoorMap="false" :zoom="zoom" :center="center" class="amap-demo">
          </el-amap>
          <!--icon标识  start-->
          <div class="icon-logo">
            <ul>
              <li>
                <i></i>
                <span>正常电梯</span>
              </li>
              <li>
                <i></i>
                <span>维保中的电梯</span>
              </li>
              <li>
                <i></i>
                <span>故障电梯</span>
              </li>
            </ul>
          </div>
          <!--icon标识  end-->
        </div>
        <!--map end-->
        <!--shape start-->
        <div class="shape">
          <!--shape-item  start-->
          <div class="shape-item pillar">
            <div class="item-box">
              <!--标题-->
              <h3>本周信息统计</h3>
              <!--图表  start-->
              <div class="shape-area shape-week">
                <!--本周信息统计  start-->
                <div class="week">
                  <ul>
                    <li>
                      <span class="sp-week-tit"><i class="point"></i>本周维保电梯部数</span>
                      <span class="sp-week-total"><i class="num">{{inforData.maintainceNum}}</i>起</span>
                    </li>
                    <li>
                      <span class="sp-week-tit"><i class="point"></i>本周新增投保电梯笔数</span>
                      <span class="sp-week-total"><i class="num">{{inforData.insureIncrNum}}</i>起</span>
                    </li>
                    <li>
                      <span class="sp-week-tit"><i class="point"></i>本周故障起数</span>
                      <span class="sp-week-total"><i class="num">{{inforData.troubleNum}}</i>起</span>
                    </li>
                    <li>
                      <span class="sp-week-tit"><i class="point"></i>本周应急事件</span>
                      <span class="sp-week-total"><i class="num">{{inforData.emergencyNum}}</i>起</span>
                    </li>
                  </ul>
                </div>
                <!--本周信息统计  end-->
              </div>
              <!--图表  end-->
            </div>
          </div>
          <!--shape-item  end-->
          <!--shape-item  start-->
          <div class="shape-item pie">
            <div class="item-box">
              <!--标题-->
              <h3>本周电梯故障率统计(单位:%)</h3>
              <!--图表  start-->
              <div class="shape-area loc-chart">
                <div class="loc-chart" style="margin-top:0px;">
                  <!--wrapper start-->
                  <div class="pie-wrapper">
                    <div id="pie" style="height:140px;">
                    </div>
                    <!--中间文字  start-->
                    <div class="font">
                      <p>截止本周</p>
                      <p>全区各类电梯</p>
                      <p><span>{{total}}</span>台</p>
                    </div>
                    <!--中间文字  end-->
                  </div>
                  <!--wrapper end-->
                </div>
              </div>
              <!--图表  end-->
            </div>
          </div>
          <!--shape-item  end-->
          <!--shape-item  start-->
          <div class="shape-item pillar">
            <div class="item-box">
              <!--标题-->
              <h3>区域故障统计(单位:起)</h3>
              <!--图表  start-->
              <div class="shape-area area-progress">
                <h4>截止本周全区各类电梯故障<span>{{totalTrouble}}</span>起</h4>
                <!--progress  start-->
                <div class="progress">
                  <ul>
                    <li v-for="(item, key, index) in troubleList">
                      <el-tooltip placement="top">
                        <div slot="content">{{item.streetName}}({{item.streetNum}})</div>
                        <span>
	                      			<i>{{item.streetName}}</i>
	                      			(<i>{{item.streetNum}}</i>起):
	                      </span>
                      </el-tooltip>
                      <el-progress :text-inside="true" :stroke-width="12" :percentage="item.num"
                                   :show-text="false"></el-progress>
                    </li>
                  </ul>
                </div>
                <!--progress  end-->
              </div>
              <!--图表  end-->
            </div>
          </div>
          <!--shape-item  end-->
        </div>
        <!--shape end-->
      </div>
    </div>
    <!--index end-->
  </div>
</template>

<script>
  // 引入vue-amap(使用高德地图)
  import VueAMap from 'vue-amap'
  import Vue from 'vue'
  import echarts from 'echarts'
  import {bus} from '../../js/brothersBus'
  import com from '../../js/common'
  import {iGetSearchList, iGetFaultList, iGetMapData} from '@/api/getData'

  Vue.use(VueAMap)
  VueAMap.initAMapApiLoader({
    key: '058102089272acff9a96cddfa5b207d0',
    plugin: ['AMap.Map', 'AMap.DistrictSearch', 'AMap.PlaceSearch',
      'AMap.Icon', 'AMap.Size', 'AMap.Pixel', 'AMap.InfoWindow', 'AMap.Text',
      'Map3D', 'AMap.Util.requestAnimFrame', 'AMap.ToolBar'],
    uiVersion: '1.0',
    v: '1.4.6'
  });
  Vue.prototype.$echarts = echarts
  window.forceWebGL = true;
  export default {
    data: function () {
      const self = this;
      return {
        searchShow: false,  // 初始情况下下拉列表关闭
        searchData: '',  // input输入值        //
        searchList: [],
        name: {
          input: 'aaa'
        },
        center: [120.141406, 30.319037],
        zoom: 11,
        radar: '',
        inforData: {          // 信息统计
          maintainNum: '',
          insureIncrNum: '',
          troubleNum: '',
          emergencyNum: '',
          normalNum: ''
        },
        troubleList: [         // 故障区域统计
        ],
        totalTrouble: '',      // 故障区域统计总数
        areaCode: '',
        total: 0,             // 全区各类电梯总台数
        markers: []
      }
    },
    mounted() {
      // 棱形
      if (!window.AMap) {
        setTimeout(_ => this.prismatic(), 1000)
      } else {
        this.prismatic()
      }
      // 搜索下拉
      this.searchFun()
      // 区域故障统计
      this.faultList()
      // 首页其他数据
      this.getMapData('')
    },
    methods: {
      prismatic() {
        var self = this;
        if (typeof window.AMap == "undefined") {
          return
        } else {
          // const self = this;
          var map = self.$refs.map.$$getInstance();
          
          setTimeout(function() {
          		var search = new AMap.DistrictSearch({
	            subdistrict: 1,
	            extensions: 'all',
	            level: 'district'
	          }).search('拱墅区', (status, result) => {
	            if (result['info'] !== 'OK') {
	              return;
	            }
	            var cetner = [result.districtList[0].center.lng, result.districtList[0].center.lat];
	            self.center = cetner;
	            var map = self.$refs.map.$$getInstance();
	            map.AmbientLight = new AMap.Lights.AmbientLight([1, 1, 1], 0.5);
	            map.DirectionLight = new AMap.Lights.DirectionLight([0, 0, 1], [1, 1, 1], 1);
	            var polygon = new AMap.Polygon({ // 覆盖物
	              map: map,
	              strokeWeight: 1,
	              path: result.districtList[0].boundaries[0],
	              fillOpacity: 0.7,
	              fillColor: '#CCF3FF',
	              strokeColor: '#CC66CC',
	            });
	            map.setFitView();
	            self.zoom = 12.6
	            const object3Dlayer = new AMap.Object3DLayer();
	            map.add(object3Dlayer);
	            var bounds = result.districtList[0].boundaries;
	            var height = 5000;
	            var color = '#0088ffcc'//rgba(50,119,233,.8)';//rgba
	            var prism = new AMap.Object3D.Prism({
	              path: bounds,
	              height: height,
	              color: color
	            });
	            prism.transparent = true;
	            setTimeout(function () {
	              object3Dlayer.add(prism)
	            }, 200)
	
	            var text = new AMap.Text({ // 覆盖物文字
	              text: '拱墅区</br>电梯分布图',
	              textAlign: 'right',
	              verticalAlign: 'bottom',
	              position: result.districtList[0].center,
	              height: 5000,
	              style: {
	                'background-color': 'transparent',
	                '-webkit-text-stroke': 'transparent',
	                '-webkit-text-stroke-width': '0',
	                'text-align': 'center',
	                'border': 'none',
	                'color': 'white',
	                'font-size': '30px',
	                'font-weight': 600
	              }
	            });
	            text.setMap(map);
	            // 文字放大缩小
	            var scroll = 0;
	            var elseCount = 0
	            var arr =[];
	            document.getElementById("amapDemo").onmousewheel= function(e) {
	            	scroll++
	    					let curZoom = self.zoom;        // 获取当前的zoom级别
								let curGetZoom = map.getZoom();   // 当前获取到的zoom级别
	            	var fixSize = 30
	            	if(scroll == 1) {  // 第一次滚动
									if(curGetZoom > curZoom) { // 放大
										console.log('放大')
										fixSize += 3
										text.setStyle({'fontSize': fixSize + 'px'})
									} else { // 缩小
										console.log('缩小')
										fixSize -= 3
										text.setStyle({'fontSize': `${fixSize}px`})
									}
	            	} else { // 不是第一次滚动
										var newArr = []
	            			arr.push({curZoom,curGetZoom})
	            			arr.forEach((i,t) => {
	        					newArr.push(arr[t].curGetZoom)
			        				if(newArr.length <2) {
			        					return
			        				} else {
			        					if(newArr[newArr.length - 1] > newArr[newArr.length - 2]) {
			        						fixSize += 3
			        						text.setStyle({'fontSize': fixSize + 'px'})
			        					} else {
			        						fixSize -= 3
			        						text.setStyle({'fontSize': fixSize + 'px'})
			        					}
			        				}
	        				})
            		}
							}
	            map.setFitView();
	          });
          },2000)
        }
      },
      searchFun() {   // 搜索下拉数据获取
        const self = this
        iGetSearchList({}).then(function (data) {
          var data = data.data.data
          self.searchList = data
        }).catch(function (data) {
          console.log('失败')
        })
      },
      faultList() {   // 区域故障统计数据获取
        const self = this
        var curTotal = 0
        iGetFaultList({}).then(function (data) {
          var data = data.data.data
          for (let item in data) {
            self.troubleList.push({
              streetName: item,
              streetNum: data[item]
            })
            curTotal = curTotal + data[item];
          }
          self.totalTrouble = curTotal
        }).catch(function (data) {
          console.log('失败')
        })
      },
      getMapData(code) {
        const self = this
        iGetMapData({
          areaCode: code
        }).then(function (data) {
          var data = data.data.data
          // 本周信息统计
          self.inforData = data
          // 饼状
          self.pie()
          self.total = data.totalNum

          // 电梯坐标点显示
          var elevatorList = data.elevatorList;
          var lnglats = [];
          var map = self.$refs.map.$$getInstance();
          map.AmbientLight = new AMap.Lights.AmbientLight([1, 1, 1], 0.5);
          map.DirectionLight = new AMap.Lights.DirectionLight([0, 0, 1], [1, 1, 1], 1);
          if (elevatorList instanceof Array) {
            if (elevatorList.length > 0) {
              // 新数组
              var curArr = [];
              elevatorList.forEach((i, t) => {
                curArr.push({
                  position: [i.lng, i.lat],
                  content: '<li class="coordinate">'
                  + '<ul>'
                  + '<li><span class="sp-name">所在小区:</span><span>' + i.name + '</span></li>'
                  + '<li><span class="sp-name">注册代码:</span><span>' + i.code + '</span></li>'
                  + '<li><span class="sp-name">维保单位:</span><span>' + i.maintainceUnit + '</span></li>'
                  + '</ul>'
                  + '</li>',
                  status: i.status
                })
              })

              // 新构建对象
              const obj = {};
              curArr.forEach(item => {
                const pos = item.position.toString();
                if (!obj[pos]) {
                  obj[pos] = item;
                  return;
                }
                if (obj[pos].content === item.content) {
                  return;
                }
                obj[pos].status = item.status >= obj[pos].status ? item.status : obj[pos].status
                obj[pos].content += item.content;
              });

              const newArr = Object.keys(obj).map(key => obj[key]);

              // 将自己的坐标点渲染到高德地图上
              var infoWindow = new AMap.InfoWindow();
              newArr.forEach((i, t) => {
                var icon;
                icon = '/static/img/index/'
                icon += ['normal.png', 'repair.png', 'fault.png'][i.status]

                var marker = new AMap.Marker({
                  map: map,
                  icon: icon,
                  position: i.position,
                  offset: new AMap.Pixel(-10, -34)
                });
                marker.content = '<div class="wrapZb"><ol>' + i.content + '</ol></div>';
                marker.on('click', function (e) {
                  infoWindow.setContent(e.target.content);
                  infoWindow.open(map, e.target.getPosition());
                })
                self.markers.push(marker);
                self.zoom = 18;
                map.setFitView();
              })
            } else {
              self.$message.error('暂无数据!');
            }

          }
          else {
            // map.remove(self.markers); // 清空markers点
            //  map.setFitView();
          }
        }).catch(function (data) {
          console.log(data)
        })
      },

      changeStatus: function () {   // searchFocus
        this.searchShow = true
      },
      onSearchItem: function (code, name) {
        const self = this
        self.searchData = name
        // 点击当前的街道,关闭列表
        self.searchShow = false
        self.getMapData(code)
        // 清空覆盖物
        self.$refs.map.$$getInstance().clearMap();
        self.$refs.map.$$getInstance().setFitView();

      },
      pie() {  // 饼状
        // 基于准备好的dom，初始化echarts实例
        let pie = this.$echarts.init(document.getElementById('pie'))
        // 绘制图表
        pie.setOption({
          tooltip: {
            trigger: 'item',
            formatter: "{b}:<br/> {c} ({d}%)",
            backgroundColor: 'rgba(0,0,0,0.6)'
          },
          legend: {
            orient: 'vertical',
            x: 'right',
            y: 'bottom',
            itemWidth: 5,
            itemHeight: 5,
            data: [
              {
                name: '正常运行电梯',
                icon: ''
              },
              {
                name: '已维保电梯',
                icon: ''
              },
              {
                name: '故障电梯',
                icon: ''
              }
            ]
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: ['50%', '85%'],   // 环状大小
              center: ['35%', '50%'],   // 位置信息
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    fontSize: '0',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: [
                {value: this.inforData.maintainceNum, name: '已维保电梯'},
                {value: this.inforData.troubleNum, name: '故障电梯'},
                {value: this.inforData.normalNum, name: '正常运行电梯'}
              ]
            }
          ],
          color: ['#E6A23B', '#F56C6C', '#67C23A']
        })
      },
      searchBtn() { // 搜索按钮
        const self = this
        if (self.searchData) {
          var nameArr = []
          self.searchList.forEach(item => {
            nameArr.push(item.areaName)
          })
          if (nameArr.indexOf(self.searchData) != -1) {
            self.searchList.forEach(item => {
              if (item.areaName == self.searchData) {
                self.getMapData(item.areaCode)
              }
            })
          } else {
            this.$message.error('该区域电梯未录入!');
          }
          // 点击当前的街道,关闭列表
          self.searchShow = false
        } else {
          this.$message.error('请输入您需要查询的电梯街道!');
        }
      }

    }
  }
</script>
<style lang="scss" scoped="scoped">
  @import '../../style/entry/index'; /*首页样式引入*/
 	
</style>
<style lang="scss">
	.amap-icon {
	  width: 20px;
	  height: 20px;
	} 
	.wrapZb{
		ol{
			li.coordinate{
				margin-bottom:15px;
				&:nth-last-child(1) {
					margin-bottom:0;
				}
				.sp-name{
					margin-right:5px;
				}
			}
		}
	}
	.amap-info-outer,.amap-info-outer:hover{
		box-shadow:0 3px 14px rgba(169,200,235,0.5);
	}
</style>
